<?php
declare(strict_types=1);

namespace App\AdminApi\Module\System\Api;

use App\AdminApi\AdminApiBasicsController;
use App\AdminApi\Module\System\Search\SmsSearch;
use App\AdminApi\Module\System\Service\SmsService;
use App\AdminApi\Module\System\Service\SmsTemplateService;
use App\Common\Model\System\SmsTemplateModel;
use App\Sys;
use Hyperf\HttpServer\Annotation\{Controller, GetMapping, PostMapping};
use Psr\Http\Message\ResponseInterface;
use Zms\Guard\Auth;
use Zms\HyperfResponse\Response;
use Zms\Validate\Type;
use function Zms\Validate\Validate;

#[
    Auth(guard: self::GUARD, label: ['系统管理', '短信记录'], app: self::APP),
    Controller(prefix: "/admin-api/system-sms", server: self::SERVER)
]
class SmsController extends AdminApiBasicsController
{
    #-----------------------------------------------------短信模板-----------------------------------------------------#
    #[
        GetMapping('template-list'),
        Auth(label: ['短信模板'], sign: 'system.sms.templateList')
    ]
    public function TemplateList(SmsTemplateService $template): ResponseInterface
    {
        return Response::Api()->success(data: $template->getSmsTemplateList());
    }

    #[
        PostMapping('update-template'),
        Auth(label: ['更新短信模板'], sign: 'system.sms.updateTemplate')
    ]
    public function UpdateTemplate(SmsTemplateService $service): ResponseInterface
    {
        $data = validate(
            [
                ['KEY', Type::REQUIRED, 'error' => '数据异常，请刷新重试'],
                ['KEY', Type::STRING],
                ['TEMPLATE_ID', Type::STRING, 'max' => 50],
                ['CONTENT', Type::REQUIRED],
                ['CONTENT', Type::STRING, 'max' => 100]
            ],
            $this->request->post(),
            [
                'KEY' => '调用名称',
                'CONTENT' => '模板内容',
                'TEMPLATE_ID' => '模板ID'
            ]
        );
        if (is_string($data)) {
            return Response::Api()->fail($data);
        }
        /**
         * @var SmsTemplateModel $template
         */
        $template = $service->search(['key' => $data['KEY']])->first();
        if (!$template) {
            $template = $service->getModel();
            $template->key = $data['KEY'];
        }
        $template->template_id = $data['TEMPLATE_ID'];
        $template->content = $data['CONTENT'];
        if ($template->save()) {
            return Response::Api()->success('短信模板设置成功');
        }
        return Response::Api()->fail('短信模板设置失败');
    }


    #-----------------------------------------------------短信记录-----------------------------------------------------#
    #[
        GetMapping('list'),
        Auth(label: ['短信发送记录'], sign: 'system.sms', view: '/system/sms/index')
    ]
    public function list(): ResponseInterface
    {
        $search = new SmsSearch([
            'where' => $this->request->inputs(['phone', 'status', 'driver', 'template_id']),
            'order' => 'id DESC',
            'page' => $this->page(),
            'size' => $this->pageSize(),
            'column' => ['id', 'phone', 'template_id', 'driver', 'status', 'content', 'send_at']
        ]);
        return Response::Api()->success(data: $search->search());
    }


    #[
        GetMapping('list-exp'),
        Auth(label: ['导出发送记录'], sign: 'system.sms.exp')
    ]
    public function ListExp(): ResponseInterface
    {
        $search = new SmsSearch([
            'where' => $this->request->inputs(['phone', 'status', 'driver', 'template_id']),
            'order' => 'id DESC',
            'page' => 1,
            'size' => 30000,
            'column' => ['phone', 'driver', 'status', 'content', 'send_at']
        ]);
        return Response::Api()->success(data: $search->export("短信发送记录"));
    }


    #-----------------------------------------------------短信配置-----------------------------------------------------#
    #[
        GetMapping('configure'),
        Auth(label: ['后台设置'], sign: 'system.sms.configure', view: '/system/sms/configure')
    ]
    public function getConfigure(SmsService $service): ResponseInterface
    {
        return Response::Api()->success(
            data: $service->getConfigureForm('sms', $this->request->getPathInfo(), '短信配置', '120px')
        );
    }

    #[
        PostMapping('configure'),
        Auth(label: ['后台设置'], relyon: ['system.sms.configure'])
    ]
    public function setConfigure(SmsService $service): ResponseInterface
    {
        $service->setConfigure('sms', $this->request->post());
        Sys::cache()->clear();
        return Response::Api()->success("设置成功");
    }
}